<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class ome_ctl_admin_reissuedoc extends desktop_controller
{
    function index()
    {
          
        $actions= array(
            'new' => array(
                'label' => '新建',
                'href' => 'index.php?app=ome&ctl=admin_reissuedoc&act=add_reissuedoc',
                    'target' => "dialog::{width:900,height:346,title:'新建补发'}",
            ),
            'approve' => array(
                'label' => '审核',
                'submit' => 'index.php?app=ome&ctl=admin_reissuedoc&act=doapprove',
                'confirm' => '你确定选中补发订单对应店铺、数量都正确嘛？', 
                 'target' => 'refresh',
            ),
            'unapprove' => array(
                'label' => '弃审',
                'submit' => 'index.php?app=ome&ctl=admin_reissuedoc&act=dounapprove',
                'confirm' => '你确定选中补发订单取消嘛？', 
                 'target' => 'refresh',
            ),
            'delete' => array(
                'label' => '删除',
                'submit' => 'index.php?app=ome&ctl=admin_reissuedoc&act=doDelete',
            ),
        );
        $filter=array();
        $params = array(
            'title' => '补发单',
            'actions' =>$actions,
            'base_filter' => $filter,
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => false ,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,
            'orderBy' => 'create_time desc',
        );
        $this->finder('ome_mdl_reissuedoc', $params);
    }
    // {"branch_id":"1","po_id":"175","total_nums":99999,"items":[{"item_id":"299","po_id":"175","product_id":"146","num":"99999","in_num":"99999","out_num":"0","price":"0.000","status":"3","barcode":"BR3136S0606","bn":"BR3136S0606","name":"\u749e\u7af9\u62bd\u7eb8S\u78016\u5305\u88c5\uff08\u7bb1\uff09","spec_info":null,"memo":null,"defective_num":"0","from_branch_num":0,"to_branch_num":0}]}
    //添加备货
    function add_reissuedoc()
    {
        $this->display('admin/reissuedoc/reissue_add.html');
    }
    /*
    *售后服务申请
    */
    function apply($order_id,$return_id='',$act = 'add')
    {
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');

        $archiveLib = kernel::single('archive_order');
        $archive_ordObj = kernel::single('archive_interface_orders');

        $oReship_item = $this->app->model ( 'reship_items' );
        $oProduct = $this->app->model ( 'return_product' );
        $product = $oProduct->dump(array('return_id'=>$return_id));
        $archiveLib = kernel::single('archive_order');
        $oOrders_item = $this->app->model ( 'order_items' );
        $order_items = $oOrders_item->getList ( '*', array ('order_id' => $order_id ,'delete'=>'false') );
        $items = $oOrders_item->getList ( '*', array ('order_id' => $order_id ) );
        
        $newItems = array();

        foreach ( $items as $k => $v )
        {
            $spec_info = $basicMaterialExtObj->dump(array('bm_id'=>$v['product_id']),'*');

            $items[$k]['spec_info'] = $spec_info['specifications'];
            $items [$k] ['effective'] =$v['nums'];//剩余数量
            $items [$k] ['num'] =$v['nums'];//申请量
            $newItems[$v['bn']] = $items[$k];
        }
        
        $items = $newItems;
        //获取参数补发店铺设置
        $reissueshop=app::get('ome')->getConf('leeman.ome.order.reissueshop');
        $shopBns=array();
        if(!empty($reissueshop))
        {
            $shopCodes=explode(",", $reissueshop);
            foreach ($shopCodes as $key => $value) {
                $shopBns[]=$value;
            }
            $shopMdl=app::get('ome')->model('shop');
            $shopData=$shopMdl->getList("*",array('shop_bn' =>$shopBns,'shop_id'=>$this->shopIds));
        }
        $this->pagedata['shop_data'] = $shopData;
        $this->pagedata['items'] = $items;
        $this->pagedata['order_id'] = $order_id;
        $this->pagedata['act'] = $act;
        $this->pagedata['finder_id'] = $_GET['finder_id']?$_GET['finder_id']:$_POST['finder_id'];

        $this->display( "admin/reissuedoc/reissue_apply.html" );
    }
    function edit($id)
    {
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');

        $reissuedoc = $this->app->model('reissuedoc');
        $reissuedocL = $this->app->model('reissuedoc_line');
        $reissuedocData=$reissuedoc->dump($id,"*");
        $archiveLib = kernel::single('archive_order');
        $oReship_item = $this->app->model ( 'reship_items' );
        $archive_ordObj = kernel::single('archive_interface_orders');
        $source = trim($_GET['source']);
        $order_id=$reissuedocData['order_id'];
        $oOrders_item = $this->app->model ( 'order_items' );
        $items = $oOrders_item->getList ( '*', array ('order_id' => $order_id,'delete'=>'false' ) );
        $newItems = array();

        //明细重新汇总
        foreach ( $items as $k => $v )
        {
            $reissueLdata=$reissuedocL->getList("*",array('reissuedoc_id' =>$id ,'item_id'=>$v['item_id'] ));
            $spec_info = $basicMaterialExtObj->dump(array('bm_id'=>$v['product_id']),'*');
            $items[$k]['spec_info'] = $spec_info['specifications'];
            $items [$k] ['effective'] =$v['nums'];//剩余数量
            $items [$k] ['num'] =$reissueLdata[0]['num'];//申请量
            if(!empty($reissueLdata))
            {
                $items[$k]['disabled']='false';   
            }
            $newItems[$v['bn']] = $items[$k];
            
        }
        
        $items = $newItems;
        //获取参数补发店铺设置
        $reissueshop=app::get('ome')->getConf('leeman.ome.order.reissueshop');
        $shopBns=array();
        if(!empty($reissueshop))
        {
            $shopCodes=explode(",", $reissueshop);
            foreach ($shopCodes as $key => $value) {
                $shopBns[]=$value;
            }
            $shopMdl=app::get('ome')->model('shop');
            $shopData=$shopMdl->getList("*",array('shop_bn' =>$shopBns,'shop_id'=>$this->shopIds));
        }
        $this->pagedata['shop_data'] = $shopData;
        $this->pagedata['items'] = $items;
        $this->pagedata['reissuedoc'] = $reissuedocData;
        $this->pagedata['order_id'] = $order_id;
        $this->pagedata['act'] = $act;
        $this->pagedata['finder_id'] = $_GET['finder_id']?$_GET['finder_id']:$_POST['finder_id'];

        $this->display( "admin/reissuedoc/reissue_apply.html" );
    }

    //售后申请保存
    function apply_add()
    {
        $this->begin('index.php?app=ome&ctl=admin_reissuedoc&act=index');
        $oOrder = $this->app->model ( 'orders' );
        $oOrder_item = $this->app->model( 'order_items' );
        $reissuedoc = $this->app->model( 'reissuedoc' );
        $reissuedoc_line = $this->app->model( 'reissuedoc_line' );
        $id=$_POST['id'];
        $order_id = $_POST ['order_id'];
        $order = $oOrder->dump ( $order_id, '*' );
        $memo = $_POST['memo'];
        $archive_ordObj = kernel::single('archive_interface_orders');
        if ($memo == '') 
        {    
            $this->end(false,'补发原因不能为空!');
        } else if (empty ( $_POST ['shop_id'] )) 
        {
            $this->end(false,'补发店铺不能为空!');
        } else if (empty ( $_POST ['goods_bn'] )) 
        {
            $this->end(false,'您没有选择商品!');
        }

        $exits = $reissuedoc->getList('*', array('order_id'=>$_POST['order_id']), 0, 1);
        if(!empty($exits))
        {
            $this->end(false,$order['order_bn'].'已存在相同订单号!');
        }
        // 获取单价
        $price = $oOrder_item->getList('*', array('order_id'=>$_POST['order_id']), 0, 1);

        $items = array ();
        foreach ( $_POST ['goods_bn'] as $key => $val ) 
        {
            $item = array ();
            $item ['bn'] = $val;
            $item ['item_id'] = $_POST ['item_id'] [$val];
            $item ['name'] = $_POST ['goods_name'] [$val];
            $item ['product_id'] = $_POST ['product_id'] [$val];
            $item ['num'] = intval ( $_POST ['num'] [$val] );
            $item ['price'] = $price[0]['price'];
            $_POST ['num'] [$val] = intval($_POST ['num'] [$val]);
            $_POST ['effective'] [$val] = intval($_POST ['effective'] [$val]);

            if ($_POST ['num'] [$val] <= 0) {
                $this->end(false,'申请数量不可以为小于1的整数!');
            }
            if ($_POST ['effective'] [$val] <= 0) {
                $this->end(false,'剩余数量不足，不可以操作!');
            } else if ($_POST ['num'] [$val] > $_POST ['effective'] [$val]) {
                $this->end(false,'申请数量大于剩余数量，不可以操作!');
            }
            $item['effective']=intval($_POST ['effective'] [$val]);
            $items [] = $item;
        }
        $aData ['order_id'] = $order_id;
        $aData ['create_time'] = time ();
        $aData ['reason'] = $_POST ['memo'];
        $aData ['status'] = 'unconfirmed';
        $aData ['shop_id'] = $_POST ['shop_id'];
        $aData ['operator']= kernel::single('desktop_user')->get_name();
        $aData ['rd_bn'] = $this->gen_id();
        if($id>0)
        {
            unset($aData['rd_bn']);
            unset($aData['create_time']);
            $aData['id']=$id;
            $reissuedoc->save($aData);   
            kernel::database()->exec("delete from sdb_ome_reissuedoc_line where reissuedoc_id in(".$id . ");");
        }else{
            $res=$reissuedoc->insert($aData);   
        }
        foreach ($items as $key => $value) 
        {
            if($id>0)
            {
                $value['reissuedoc_id']=$id;   
            }else{
                $value['reissuedoc_id']=$res;   
            }
            $reissuedoc_line->insert($value);
        }
        $finder_id = $_GET['finder_id'];
        $this->end(true,"补发单{".$aData ['rd_bn'] ."}生成成功!",'javascript:$("return-apply").getParent(".dialog").retrieve("instance").close();finderGroup["'.$finder_id.'"].refresh();');
    }
    /*
     * 生成调整单号
     * @return 补发单号
     */
    function gen_id(){
        $i = rand(0,9999);
        do{
            if(9999==$i){
                $i=0;
            }
            $i++;
            $rd_bn = date("YmdH").'13'.str_pad($i,6,'0',STR_PAD_LEFT);
            $row = kernel::database()->selectrow('select rd_bn from sdb_ome_reissuedoc where rd_bn =\''.$rd_bn.'\'');
        }while($row);
        return $rd_bn;
    }
    //取消动作
    function dounapprove()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=ome&ctl=admin_reissuedoc&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条取消生成！');
        }
        //add by ldward 20181128取消操作
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('reissuedoc');
        $orderMdl=app::get('ome')->model('orders');
        $db=kernel::database();

        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='confirmed')
        {   
            $this->end(false, '状态异常，无法取消补发订单！');
        }
        $oOrder=$orderMdl->dump($spdata['new_order_id'],"*");
        if($oOrder['process_status']!='unconfirmed')
        {
            $this->end(false, '补发订单'.$spdata['new_order_bn'].'已处理，请确认！！');
        }

        $db->exec("update sdb_ome_orders set process_status='cancel',relate_order_bn='',last_modified='".time()."' where  order_id in(" . $spdata['new_order_id'] . ");"); 
        $db->exec("update sdb_ome_reissuedoc set status='cancel',operator='".kernel::single('desktop_user')->get_name()."',last_modify='".time()."' where  id in(" . $id . ");"); 
        $this->end(true, '取消成功！');
    }
    //删除动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=ome&ctl=admin_reissuedoc&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $spMdl = $this->app->model('reissuedoc');

        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key => $order) 
            {
                $value = $order['id'];
                $spdata = $spMdl->dump($value,"*");
                if ($spdata['status'] == 'unconfirmed') 
                {
                    $spMdl->db->exec("delete from sdb_ome_reissuedoc_line where reissuedoc_id in(".$value . ");");
                    $spMdl->db->exec("delete from sdb_ome_reissuedoc  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '补发单号【' . $spdata['rd_bn'] . '】状态异常，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) 
            {
                $spdata = $spMdl->dump($value,"*");

                if ($spdata['status'] == 'unconfirmed') 
                {
                    $spMdl->db->exec("delete from sdb_ome_reissuedoc_line where reissuedoc_id in(" . $value . ");");
                    $spMdl->db->exec("delete from sdb_ome_reissuedoc where id in(" . $value . ");");
                } else {
                    $this->end(false, '补发单号【' . $spdata['rd_bn'] . '】状态异常，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }
   
    //审核动作
    function doapprove()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=ome&ctl=admin_reissuedoc&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条生成！');
        }
        //add by ldward 20181128生成明细
        $id=$postData['id'][0];
        $rdocMdl = $this->app->model('reissuedoc');
        $rdocMdlL = $this->app->model('reissuedoc_line');
        $orderMdl=app::get('ome')->model('orders');
        $orderItems=app::get('ome')->model('order_items');
        $orderObjects=app::get('ome')->model('order_objects');
        $shopMdl=app::get('ome')->model('shop');
        $db=kernel::database();

        $rDocdata=$rdocMdl->dump($id,"*");  
        $oOrder=$orderMdl->dump($rDocdata['order_id'],"*");
        $shopData=$shopMdl->dump($rDocdata['shop_id'],"*");
        $rDocLdata=$rdocMdlL->getList('*', array('reissuedoc_id' => $id ));

        if($spdata['status']=='confirmed')
        {   
            $this->end(false, '已审核生成补发单，请确认！');
        }
        if(empty($oOrder))
        {
            $this->end(false, '对应订单不存在，请确认！');
        }
        //构造订单数据
        $aData =  array(//一条订单信息
            'member_id' => $oOrder['member_id'], //购买人 默认  admin
            'address_id' => $oOrder['consignee']['area'],
            'consignee' => array(
                'area' => $oOrder['consignee']['area'],
                'addr' => $oOrder['consignee']['addr'],
                'name' => $oOrder['consignee']['name'],
                'zip' => $oOrder['consignee']['zip'],
                'mobile' => $oOrder['consignee']['mobile'],
                'telephone' => $oOrder['consignee']['telephone'],
            ),
            'shop_id' => $shopData['shop_bn'], //店铺ID
            'is_cod' => false,
            'is_tax' => false,
            'branch_id' => '',
            'customer_memo' => '',
            'cost_shipping' => '',
            'tax_title' => '',
            'disc' => '',
            'discount' => '',
            'relate_order_bn' => $oOrder['order_bn'],
            'order_memo' => '',
            'paytime' => $oOrder['paytime'],//付款时间
            'payment'=>$oOrder['payment'],
        );
        //查询obj中则为销售物料编码
        foreach ($rDocLdata as $key => $value) 
        {
            $itemDatas=$orderItems->dump($value['item_id'],'obj_id');
            $objData= $orderObjects->dump($itemDatas['obj_id'],"*");
            $aData['goods'][] = array(
                    'bn' => $objData['bn'], //商品编号
                    'num' => $value['num'], //数量
                    'price' =>$value['price'], //销售金额
                );
        }
        $res=$this->doAddNormalOrder($aData);
        if(!empty($res))
        {
            $db->exec("update sdb_ome_reissuedoc set status='confirmed',operator='".kernel::single('desktop_user')->get_name()."',new_order_id='".$res['order_id']."',new_order_bn='".$res['order_bn']."',
                last_modify='".time()."' where  id in(".$id.");");             
        }else 
        {
            $this->end(false, '订单生成失败！');
        }

        $this->end(true, '已完成');
    }
    function doAddNormalOrder($data)
    {
        $import_data = $data;
        $salesMLib = kernel::single('material_sales_material');
        $oObj = $this->app->model("orders");

        $is_code = false;
        $weight = 0;
        $item_cost = 0;
        $post = $import_data;
        $post['consignee']['r_time'] = '任意日期 任意时间段';
        $post['consignee']['area'] = $post['address_id'];

        $post['member_id'] = $post['member_id'];
        
        if (!$post['cost_shipping'])
            $post['cost_shipping'] = 0;
        if (!$post['discount'])
            $post['discount'] = 0;

        $consignee = $post['consignee'];
        if ($consignee) {
            if (!$consignee['name']) {
            }
            if (!$consignee['area']) {
            }
            if (!$consignee['addr']) {
            }
            if (!$consignee['mobile'] && !$consignee['telephone']) 
            {
            }
        } else {
        }
        $ship = $import_data['address_id'];
        #检测是不是货到付款
        if ($post['is_cod'] == 'true' || $post['is_cod'] == 'false') {
            $is_code = $post['is_cod'];
        }
        $shipping = array();
        if ($ship) {
            $shipping = array(
                'shipping_name' => '快递',
                'cost_shipping' => $post['cost_shipping'],
                'is_protect' => 'false',
                'cost_protect' => 0,
                'is_cod' => $is_code ? $is_code : 'false'
            );
        }
        $iorder = $post['order'];
        $iorder['consignee'] = $consignee;
        $iorder['shipping'] = $shipping;
        if ($post['shop_id']) {
            $shop = explode('*', $post['shop_id']);
            $iorder['shop_id'] = $shop[0];
            $iorder['shop_type'] = $shop[1];
            $sObj = $this->app->model("shop");
            $iorder_shop = $sObj->getRow(array('shop_bn' => $iorder['shop_id']));
            $iorder['shop_id'] = $iorder_shop['shop_id'];
            $iorder['shop_type'] = $iorder_shop['shop_type'];
        } else {
            $this->api_view(false, '请选择来源店铺！');
        }
        //检查关联订单
        $iorder_bn = $oObj->getRow(array('relate_order_bn' => $post['relate_order_bn']));
        if (!empty($iorder_bn)) {
            $this->api_view(false, '关联订单号已存在！');
        }
        //读取商品信息，组合数据
        $num = $post['goods'];
        if (!$num)
            $this->api_view(false, '请选择商品');
        foreach ($num as $k => $v) {
            if ($v['price'] < 0) {
                $this->api_view(false, '请填写正确的价格');
            }
            if ($v['num'] < 0) {
                $this->api_view(false, '数量必须大于1');
            }
            $salesMInfo = $salesMLib->getSalesMByBn($iorder['shop_id'], $v['bn']);
            if ($salesMInfo) {
                //获取绑定的基础物料
                $basicMInfos = $salesMLib->getBasicMBySalesMId($salesMInfo['sm_id']);
                $obj_number = $v['num'];
                $obj_price = $v['price'];
                //如果是促销类销售物料
                if ($salesMInfo['sales_material_type'] == 2) {
                    $obj_type = 'pkg';
                    $obj_sale_price = $obj_price * $obj_number;
                    //item层关联基础物料平摊销售价
                    $salesMLib->calProSaleMPriceByRate($obj_sale_price, $basicMInfos);

                    foreach ($basicMInfos as $kk => $basicMInfo) {
                        $order_items[] = array(
                            'product_id' => $basicMInfo['bm_id'],
                            'bn' => $basicMInfo['material_bn'],
                            'name' => $basicMInfo['material_name'],
                            'price' => $basicMInfo['rate_price'] ? bcdiv($basicMInfo['rate_price'], $basicMInfo['number'] * $obj_number, 2) : 0.00,
                            'amount' => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                            'sale_price' => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                            'quantity' => $basicMInfo['number'] * $obj_number,
                            'divide_order_fee'=>$obj_number*$obj_price ,
                            'sendnum' => 0,
                            'item_type' => 'pkg'
                        );

                        $weight += $basicMInfo['weight'] * $basicMInfo['number'] * $obj_number;
                    }
                } else {
                    $obj_type = ($salesMInfo['sales_material_type'] == 1) ? 'goods' : 'gift';
                    $item_type = ($obj_type == 'goods') ? 'product' : 'gift';

                    if ($obj_type == 'gift') {
                        $obj_price = 0.00;
                    }

                    foreach ($basicMInfos as $kk => $basicMInfo) {
                        $order_items[] = array(
                            'product_id' => $basicMInfo['bm_id'],
                            'bn' => $basicMInfo['material_bn'],
                            'name' => $basicMInfo['material_name'],
                            'price' => $obj_price,
                            'amount' => $obj_price * $obj_number,
                            'sale_price' => $obj_price * $obj_number,
                            'quantity' => $basicMInfo['number'] * $obj_number,
                            'divide_order_fee'=>$obj_number*$obj_price ,
                            'sendnum' => 0,
                            'item_type' => $item_type
                        );

                        $weight += $basicMInfo['weight'] * $basicMInfo['number'] * $obj_number;
                    }
                }

                $iorder['order_objects'][] = array(
                    'obj_type' => $obj_type,
                    'obj_alias' => $obj_type,
                    'goods_id' => $salesMInfo['sm_id'],
                    'bn' => $salesMInfo['sales_material_bn'],
                    'name' => $salesMInfo['sales_material_name'],
                    'price' => $v['price'],
                    'sale_price' => $v['price'] * $obj_number,
                    'divide_order_fee'=>$obj_number*$obj_price ,
                    'amount' => $v['price'] * $obj_number,
                    'quantity' => $obj_number,
                    'order_items' => $order_items
                );

                $item_cost += $v['price'] * $obj_number;
                unset($order_items);
            } else {
                $this->api_view(false, '店铺无对应物料信息：' . $v['bn']);
            }
        }

        if ($post['customer_memo']) {
            $c_memo = htmlspecialchars($post['customer_memo']);
            $c_memo = array('op_name' => kernel::single('desktop_user')->get_name(), 'op_time' => date('Y-m-d H:i', time()), 'op_content' => $c_memo);
            $tmp[] = $c_memo;
            $iorder['custom_mark'] = serialize($tmp);
            $tmp = null;
        }
        if ($post['order_memo']) {
            $o_memo = htmlspecialchars($post['order_memo']);
            $o_memo = array('op_name' => kernel::single('desktop_user')->get_name(), 'op_time' => date('Y-m-d H:i', time()), 'op_content' => $o_memo);
            $tmp[] = $o_memo;
            $iorder['mark_text'] = serialize($tmp);
            $tmp = null;
        }


        $mathLib = kernel::single('eccommon_math');

        $iorder['member_id'] = $post['member_id'];
        $iorder['weight'] = $weight;
        $iorder['title'] = $p['bn'] . $p['name'];
        $iorder['itemnum'] = count($iorder['order_objects']);
        $iorder['createtime'] = time();
        $iorder['ip'] = $_SERVER['REMOTE_ADDR'];
        $iorder['cost_item'] = $item_cost;
        $iorder['currency'] = 'CNY';
        $iorder['pmt_order'] = $post['pmt_order'];
        $iorder['discount'] = $post['discount'];
        $iorder['relate_order_bn'] = $post['relate_order_bn'];
        $iorder['total_amount'] = $mathLib->number_plus(array($item_cost, $post['cost_shipping'], $post['discount']));
        $iorder['total_amount'] = $mathLib->number_minus(array($iorder['total_amount'], $post['pmt_order']));
        // $iorder['total_amount'] = $item_cost+$post['cost_shipping']-$post['pmt_order']+$post['discount'];

        $iorder['is_delivery'] = 'Y';
        $iorder['source'] = 'local'; //订单来源标识，local为本地新建订单
        $iorder['createway'] = 'local';

        $iorder['pay_status'] = '1';
        $iorder['payed'] = $iorder['total_amount'];
        $iorder['paytime']=$post['paytime'];
        $iorder['payment']=$post['payment'];
        $iorder['is_reissue']=true;
        #新建订单时，要开票的
        if ($post['is_tax'] == 'true') {
            $iorder['is_tax'] = $post['is_tax'];
            $iorder['tax_title'] = $post['tax_title'];
        }

        if ($iorder['total_amount'] < 0)
            $this->api_view(false, '订单金额不能小于0');

        $iorder['order_bn'] = $oObj->gen_id();
        $iorder['download_time'] = time();

        //设置订单失败时间
        $iorder['order_limit_time'] = time() + 60 * (app::get('ome')->getConf('ome.order.failtime'));

        $oObj->create_order($iorder);
        #货到付款类型订单，增加应收金额
        if ($is_code == 'true') {
            $oObj_orextend = $this->app->model("order_extend");
            $code_data = array('order_id' => $iorder['order_id'], 'receivable' => $iorder['total_amount'], 'sellermemberid' => $iorder['member_id']);
            $oObj_orextend->save($code_data);
        }
        return  array('order_id' => $iorder['order_id'],'order_bn'=>$iorder['order_bn'] );
    }
    function api_view($type, $msg)
    {
        $this->end($type, $msg);
    }

}



